package com.tanhua.sso.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.sso.config.AliyunConfig;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * 图片上传
 */
@Service
public class PicUploadService {

    private static final String[] IMAGE_TYPE = {".jpg",".jpeg",".gif",".png",".bmp"};

    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private OSSClient ossClient;

    public PicUploadResult upload(MultipartFile uploadFile){
        // 获取一个返回给前端的对象
        PicUploadResult uploadResult = new PicUploadResult();

        Boolean isLegal = false;

        // 遍历判断是否为指定文件类型
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),type)) {
                isLegal = true;
                break;
            }
        }

        // 判断,如果没有指定类型,返回error
        if (!isLegal){
            uploadResult.setStatus("error");
            return uploadResult;
        }

        // 给文件整个新的路径 格式为 images/yyyy/MM/dd/文件名.文件格式
        String filename = uploadFile.getOriginalFilename();
        String filePath = getFilePath(filename);

        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filePath,new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            // 出异常即上传失败
            e.printStackTrace();
            uploadResult.setStatus("error");
            return uploadResult;
        }

        // 上传成功
        uploadResult.setStatus("done");
        // 设置文件名
        uploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        uploadResult.setUid(String.valueOf(System.currentTimeMillis()));

        return uploadResult;
    }

    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/"
                + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
        //  StringUtils.substringAfterLast(sourceFileName, ".");
        //  取指定字符之后的字符串,此处是取传递进来的文件名,"."后即是文件后缀名
    }
}
